//
//  HXEditOpinionViewController.m
//  KD
//
//  Created by ifly on 16/8/10.
//  Copyright © 2016年 Whx. All rights reserved.
//

#import "HXEditOpinionViewController.h"
#import "HXUpDataImageModel.h"

@interface HXEditOpinionViewController ()<UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic,strong) UIScrollView *backScrollView;
@property (nonatomic,strong) UILabel * placeHoldLabel;
@property (nonatomic,strong) UITextView * contentOneTextView;
@property (nonatomic,strong) UILabel * titleLabelTwo;
@property (nonatomic,strong) UIScrollView * imageScrollView;
@property (nonatomic,strong) UILongPressGestureRecognizer *longPress;
@property (nonatomic,strong) HXUpDataImageModel *dict;
@property (nonatomic,strong) NSMutableArray *phothMuArray;//图片数组
@property (nonatomic,strong) NSMutableArray *photoFilePathArr;//图片网址数组
@property (nonatomic,strong) UIButton *photoBtn;
@property (nonatomic,strong) UIButton * tijiaoBtn;


@property (nonatomic,copy) NSString * QueText;
@property (nonatomic,copy) NSString * SceneText;

@end

@implementation HXEditOpinionViewController

/**QueText:为25接口的DataText SceneText:为26接口的DataText*/
-(instancetype)initWithQueText:(NSString *)QueText
                 withSceneText:(NSString *)SceneText{

    if ([super init]) {
        
        UIStoryboard * editVc = [UIStoryboard storyboardWithName:@"Me" bundle:nil];
        self = [editVc instantiateViewControllerWithIdentifier:@"HXEditOpinionViewController"];
        
        self.QueText   = QueText;
        self.SceneText = SceneText;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"意见反馈";
    //self.view.backgroundColor = [UIColor goldenrod];
    
    CGRect frame = CGRectMake(0, 0, HXSCREEN_WIDTH, HXSCREEN_HEIGHT);
    _backScrollView = [[UIScrollView alloc] initWithFrame:frame];
    //_backScrollView.backgroundColor = [UIColor orangeRed];
    
    [self.view addSubview:_backScrollView];
    
    [self pageComposition];
}

/**
 界面布局
 */
-(void)pageComposition {
    
    UILabel * titleLabelOne = [[UILabel alloc] initWithFrame:CGRectMake(8, 8, HXSCREEN_WIDTH - 16, 24)];
    titleLabelOne.text = @"问题和意见";
    titleLabelOne.font = [UIFont systemFontOfSize:17];
    //titleLabelOne.layer.borderColor = [UIColor lightGrayColor].CGColor;
    //titleLabelOne.layer.borderWidth = 0.5;
    //titleLabelOne.backgroundColor = [UIColor lightGrayColor];
    [self.backScrollView addSubview:titleLabelOne];
    
    _contentOneTextView = [[UITextView alloc] initWithFrame:CGRectMake(8, titleLabelOne.bottom + 10, HXSCREEN_WIDTH - 16, 100)];
    _contentOneTextView.backgroundColor = [UIColor clearColor];
    _contentOneTextView.font = [UIFont systemFontOfSize:14];
    _contentOneTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _contentOneTextView.layer.borderWidth = 0.5f;
    _contentOneTextView.delegate = self;
    [self.backScrollView addSubview:_contentOneTextView];
    
    //placeHoldLabel
    _placeHoldLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, _contentOneTextView.top + 8, HXSCREEN_WIDTH - 16, 18)];
    _placeHoldLabel.text = @"  请简要描述你的问题和意见";
    _placeHoldLabel.textColor = [UIColor lightGrayColor];
    _placeHoldLabel.textAlignment = NSTextAlignmentLeft;
    //_placeHoldLabel.layer.borderColor = [UIColor lightGrayColor].CGColor;
    //_placeHoldLabel.layer.borderWidth = 0.5f;
    _placeHoldLabel.font = [UIFont systemFontOfSize:14];
    [self.backScrollView addSubview:_placeHoldLabel];
    
    _titleLabelTwo = [[UILabel alloc] initWithFrame:CGRectMake(8, _contentOneTextView.bottom + 25, HXSCREEN_WIDTH - 16, 24)];
    _titleLabelTwo.text = @"图片(选填,提供问题截图)";
    _titleLabelTwo.font = [UIFont systemFontOfSize:17];
    _titleLabelTwo.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _titleLabelTwo.layer.borderWidth = 0.5;
    //_titleLabelTwo.backgroundColor = [UIColor lightGrayColor];
    [self.backScrollView addSubview:_titleLabelTwo];
    
    //照片墙
    [self setImageScrollViewWithBtn];
    
    //上传按钮
    _tijiaoBtn = [[UIButton alloc] initWithFrame:CGRectMake(8, _imageScrollView.bottom + 24, _titleLabelTwo.width, 32)];
    _tijiaoBtn.backgroundColor = [UIColor blueColor];
    [_tijiaoBtn setTitle:@"提交反馈" forState:UIControlStateNormal];
    [_tijiaoBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.backScrollView addSubview:_tijiaoBtn];
    [_tijiaoBtn addTarget:self action:@selector(tijiaoBtnAct) forControlEvents:UIControlEventTouchUpInside];
}

/**发布按钮*/
-(void)tijiaoBtnAct{

    if (self.contentOneTextView.text.length <= 0) {
        
        [LTAlertView showTitle:@"请完善反馈信息,谢谢!"
                       message:nil
                  ButtonTitles:@[@"确定"] OnTapBlock:^(LTAlertView *alert, NSInteger num) {
                      
                  }];
        
        return;
    }
    
    [NetworkAPI sendFeedBackAddFeedBackWithQueText:self.QueText
                                     withSceneText:self.SceneText
                                  withFeedbackText:self.contentOneTextView.text
                                       withPicList:self.photoFilePathArr
                                           Success:^(HXBaseModel *result) {
                                               if ([result.code integerValue] == 200) {
                                                   [SVProgressHUD showSuccessWithStatus:@"非常感谢您的反馈,您的问题我们会尽快处理,谢谢!"];
                                                   [self.navigationController popToRootViewControllerAnimated:YES];
                                               }
                                               
                                           } failure:^(NSError *err) {
                                               [SVProgressHUD showErrorWithStatus:@"网络错误!"];
                                           }];
}


-(void)textViewDidChange:(UITextView *)textView {
    
    if (textView.text.length > 0) {
        _placeHoldLabel.text = @"";
    }
    else if (textView.text.length == 0) {
        _placeHoldLabel.text = @"  请简要描述你的问题和意见";
        
    }
    
    CGFloat contentOneHight = [self.contentOneTextView.text heightWithFont:[UIFont systemFontOfSize:14] withinWidth:HXSCREEN_WIDTH - 32];
    if (contentOneHight > 100) {
        CGRect oldFrame = self.contentOneTextView.frame;
        oldFrame.size.height = contentOneHight;
        self.contentOneTextView.frame = oldFrame;
        _titleLabelTwo.frame = CGRectMake(8, _contentOneTextView.bottom + 15, HXSCREEN_WIDTH - 16, 24);
        _imageScrollView.frame = CGRectMake(0, _titleLabelTwo.bottom + 20, HXSCREEN_WIDTH, 100);
        _tijiaoBtn.frame = CGRectMake(8, _imageScrollView.bottom + 24, _titleLabelTwo.width, 32);
    }
}

/**
 上传图片背景
 */
-(void)setImageScrollViewWithBtn {
    
    _imageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, _titleLabelTwo.bottom + 20, HXSCREEN_WIDTH, 100)];
    [self.backScrollView addSubview:_imageScrollView];
    UIButton * addPhotoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addPhotoBtn.tag = 100;
    addPhotoBtn.frame = CGRectMake(10, 0, 100, 100);
    [addPhotoBtn setImage:[UIImage imageNamed:@"addimageshadow"] forState:UIControlStateNormal];
    [addPhotoBtn addTarget:self action:@selector(addPhotoBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_imageScrollView addSubview:addPhotoBtn];
    //长按手势
    _longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pictureLongPress:)];
    [_imageScrollView addGestureRecognizer:_longPress];
}

-(void)addPhotoBtnClick {
    [self.contentOneTextView resignFirstResponder];
    
    CTActionSheet *actionSheet = [CTActionSheet actionSheetWithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从相机相册选择" HandleBlock:^(int btnIndex) {
        if (btnIndex == 0) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
                picker.delegate = self;
                picker.allowsEditing = YES;//设置可编辑
                picker.sourceType = sourceType;
                [self presentViewController:picker animated:YES completion:^{
                }];//进入照相界面
            }
        }else if (btnIndex == 1){
            UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
            }
            pickerImage.delegate = self;
            pickerImage.allowsEditing = YES;
            [self presentViewController:pickerImage animated:YES completion:^{
            }];
        }else{
        }
    }];
    UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
    if ([window.subviews containsObject:self.view]) {
        [actionSheet showInView:self.view];
    } else {
        [actionSheet showInView:window];
    }
}

//拿到照片
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *originalImage =  (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
    if(!originalImage){
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    [self sendUpImage:originalImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    
}

/**
 上传照片
 */
-(void)sendUpImage:(UIImage *)image {
    
    NSData *imageData = UIImageJPEGRepresentation(image, 1);
    if  (imageData.length>300000){
        UIImage *image = [UIImage imageWithData:imageData];
        imageData = UIImageJPEGRepresentation(image, 0.005);
    }
    [self.phothMuArray addObject:image];
    [self setPhotoInScrollView];
    
    //1。创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObjectsFromArray:@[@"application/json", @"text/json",@"text/html", @"text/javascript", @"text/plain"]];
    [manager POST:[NSString stringWithFormat:@"%@/FeedBack/SendPic.ashx",API_HOST] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"img" fileName:@"name" mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        _dict = [[HXUpDataImageModel alloc]initWithDictionary:responseObject error:nil];
        if ([_dict.code isEqualToString:@"200"]) {
            [SVProgressHUD showSuccessWithStatus:@"图片上传成功"];
            //图片网址_dict.FilePath
            NSDictionary * photoPath = @{
                                         @"Files_Path":_dict.FilePath
                                         };
            [self.photoFilePathArr addObject:photoPath];
            
        }
        else{
            [SVProgressHUD showErrorWithStatus:@"图片上传失败"];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"图上传失败"];
    }];
}

/**
 设置scrollView
 */
-(void)setPhotoInScrollView {
    for (int i = 0; i<self.phothMuArray.count; i++) {
        _photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _photoBtn.tag = 1001 + i;
        _photoBtn.frame = CGRectMake(10 + 110 * (i + 1), 0, 100, 100);
        [_photoBtn setImage:self.phothMuArray[i] forState:UIControlStateNormal];
        [_photoBtn addTarget:self action:@selector(photoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_imageScrollView addSubview:_photoBtn];
    }
    _imageScrollView.contentSize = CGSizeMake(110 * (self.phothMuArray.count + 1), 100);
}

-(void)photoBtnClick:(UIButton *)btn {
    
    NSLog(@"btn.tag-----------%ld",btn.tag);
}


-(void)pictureLongPress:(UILongPressGestureRecognizer *)longPress {
    
    NSMutableArray * arrayLast = [[NSMutableArray alloc] init];
    CGPoint point = [longPress locationInView:self.imageScrollView];
    NSString * strPoint =NSStringFromCGPoint(point);
    NSArray * array = [strPoint componentsSeparatedByString:@","];
    NSArray * arrayTwo = [array[0] componentsSeparatedByString:@"{"];
    for (int i = 0; i <= 20; i++) {
        if ([arrayTwo[1] intValue] > (110*i+10)) {
            [arrayLast addObject:[NSString stringWithFormat:@"%d",i]];
        }
    }
    NSString * removeIndexStr = [NSString stringWithFormat:@"%@",[arrayLast lastObject]];
    
    if ([removeIndexStr integerValue] > self.phothMuArray.count) {
        NSLog(@"揍你");
    }
    else {
        if ([removeIndexStr isEqualToString:@"0"]) {
            NSLog(@"%@",removeIndexStr);
        }
        else {
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否删除照片"
                                                                                      message:@""
                                                                               preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction * cancelButton = [UIAlertAction actionWithTitle:@"取消"
                                                                    style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction *action) {
                                                                      NSLog(@"取消");
                                                                  }];
            UIAlertAction * creationBtn = [UIAlertAction actionWithTitle:@"删除"
                                                                   style:UIAlertActionStyleDestructive
                                                                 handler:^(UIAlertAction * _Nonnull action) {
                                                                     [_imageScrollView removeFromSuperview];
                                                                     _imageScrollView = nil;
                                                                     [self.photoFilePathArr removeObjectAtIndex:[removeIndexStr integerValue] - 1];
                                                                     [self.phothMuArray removeObjectAtIndex:[removeIndexStr integerValue] - 1];
                                                                     if (_photoBtn.tag == 1000 + [removeIndexStr integerValue]) {
                                                                         [_photoBtn removeFromSuperview];
                                                                     }
                                                                     [self setImageScrollViewWithBtn];
                                                                     [self setPhotoInScrollView];
                                                                 }];
            [alertController addAction:cancelButton];
            [alertController addAction:creationBtn];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];

        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSMutableArray *)photoFilePathArr {
 
    if (_photoFilePathArr == nil) {
        _photoFilePathArr = [[NSMutableArray alloc] init];
    }
    return _photoFilePathArr;
}
-(NSMutableArray *)phothMuArray {
    if (_phothMuArray == nil) {
        _phothMuArray = [[NSMutableArray alloc] init];
    }
    return _phothMuArray;
}


@end
